<template>
  <div>
    <div>
      <form-panel ref="formPanel" :list="fromList" :cols="2" labelWidth="130" :isSubmitBtn="false"></form-panel>
      <el-upload
        style="width:50%"
        action="/api/file/oss/upload"
        :on-preview="this.handlePreview"
        :on-remove="this.handleRemove"
        :before-remove="this.beforeRemove"
        :on-success="this.handleSuccess"
        :on-exceed="handleExceed"
        accept=".jpg,.png,.pdf,.xls,.xlsx,.rar"
        :limit="1"
        :file-list="this.fileList"
        :disabled="newStatus"
      >
        <el-button size="small" type="primary" :disabled="newStatus">点击上传</el-button>
        <div slot="tip" class="el-upload__tip" :disabled="newStatus">附件支持上传excel、PDF、RAR、JPG格式</div>
      </el-upload>
    </div>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <AjaxButton type="primary" :disabled="newStatus" :click="saveDialog">保 存</AjaxButton>
      <AjaxButton type="primary" :disabled="submitEnable" :click="submit">提 报</AjaxButton>
      <el-button @click="closeDialog">关 闭</el-button>
    </div>
    <!-- 车辆选择 -->
    <BaseDialog :visible.sync="isShowGdcx" title="vin查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 70px)', overflow: 'auto', paddingBottom: '70px' }">
      <vinModal @saveDialog="confirmGdcx" @closeDialog="isShowGdcx = false"></vinModal>
    </BaseDialog>
  </div>
</template>

<script>
import FormPanel from '../../../../components/FormPanel/FormPanel.vue';
import vinModal from './vinModal.vue';
import { applyWarrantyDateChange } from '@/api/repair/repairBusiness/warrantyDateModify/index.js';
import moment from 'moment';
import SERVER from '@/api/server';
import { getConfigHeaders } from '@/api/fetch';
import axios from '@/api/fetch';
import Cookies from 'js-cookie';
export default {
  components: { FormPanel, vinModal },
  props: ['row', 'type'],
  data() {
    return {
      fromList: this.createFromList(),
      changeId: undefined,
      isShowGdcx: false,
      fileList: [],
      getConfigHeaders: getConfigHeaders,
      roNo: '',
      newStatus: false // 保存成功更新状态，不允许再编辑
    };
  },
  computed: {
    submitEnable() {
      return !!!this.fromList.find(x => x.fieldName === 'changeNo').initialValue;
    }
    // newStatus() {
    //   // 已拒绝 已通过 已提报
    //   return this.row.status == '99931002' || this.row.status == '99931004' || this.row.status == '99931005';
    // }
  },
  mounted() {
    if (this.type == 'edit') {
      this.fromList.forEach(x => {
        x.initialValue = this.row[x.fieldName];
      });
      if (this.row.url) {
        this.fileList.push({ name: this.row.name, url: this.row.url });
      }
      this.changeId = this.row.changeId;
    }
  },
  methods: {
    createFromList() {
      return [
        {
          type: 'INPUT',
          label: '保修日期变更申请单号',
          fieldName: 'changeId',
          disabled: true,
          hidden: true,
          initialValue: undefined
        },
        {
          type: 'INPUT',
          label: '保修日期变更申请单号',
          fieldName: 'changeNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          disabled: this.type == 'edit',
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
          readonly: true,
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={() => (this.isShowGdcx = true)}></el-button>;
          }
        },

        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'ownerName',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '申请人',
          fieldName: 'changeUserName',
          initialValue: Cookies.get('username') || '',
          disabled: true
        },
        {
          type: 'DATE',
          label: '申请时间',
          fieldName: 'changeDate',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          dateType: 'datetime',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'DATE',
          label: '原保修开始日期',
          fieldName: 'beforeBeginDate',
          format: 'yyyy-MM-dd',
          dateType: 'date',
          initialValue: '',
          disabled: true
        },
        {
          type: 'DATE',
          label: '原保修结束日期',
          fieldName: 'beforeEndDate',
          format: 'yyyy-MM-dd',
          dateType: 'date',
          initialValue: '',
          disabled: true
        },
        {
          type: 'DATE',
          label: '变更后保修开始日期',
          fieldName: 'afterBeginDate',
          format: 'yyyy-MM-dd',
          dateType: 'date',
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
          disabled: false,
          change: val => {
            // this.fromList.find(x => x.fieldName === 'afterEndDate').minDateTime = val;
          }
        },
        {
          type: 'DATE',
          label: '变更后保修结束日期',
          fieldName: 'afterEndDate',
          format: 'yyyy-MM-dd',
          dateType: 'date',
          disabled: false,
          rules: [{ required: true, message: '请输入', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '申请原因',
          fieldName: 'remark',
          maxlength: 45,
          disabled: false,
          rules: [{ required: true, message: '请输入', trigger: 'blur' }]
        }
      ];
    },
    handleExceed() {
      this.$notify.warning(`只能上传1个附件。如需更新附件，请先删除之前上传的附件`);
    },

    handleSuccess(response, file, fileList) {
      if (response.data) {
        this.fileList.push({ name: file.name, url: response.data });
        this.$notify.success({ title: '提示信息', message: '附件上传成功！！！' });
      } else {
        this.fileList = [];
        this.$notify.error({ title: '提示信息', message: '附件上传失败！！！' });
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = [];
    },
    handlePreview(file) {
      let fullUrl = file.url;
      const downloadElement = document.createElement('a');
      downloadElement.style.display = 'none';
      downloadElement.href = fullUrl;
      downloadElement.download = file.name; //下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    async saveDialog(type) {
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      if (type === 'submit') {
        data.changeId = this.changeId;
        data.status = 99931002; // 提报
      } else {
        data.changeId = this.changeId;
        data.status = this.type === 'add' ? 99931001 : this.row.status; // 保存
      }
      console.log(this.fileList, 'this.fileList');
      if (this.fileList.length) {
        data.fileName = this.fileList[0].name;
        data.fileAddr = this.fileList[0].url;
      }

      if (moment(data.afterBeginDate).valueOf() > moment(data.afterEndDate).valueOf()) {
        this.$notify.error({ title: '提示', message: '结束时间不能早于开始时间！！！' });
        return;
      }
      data.roNo = this.roNo;

      let res = await applyWarrantyDateChange(data);

      if (res.resultCode === 200) {
        // 回写里程变更申请单号
        this.fromList.find(x => x.fieldName === 'changeNo').initialValue = res.data.changeNo;
        this.changeId = res.data.changeId;
        if (type === 'submit') {
          this.$notify.success({ type: '提示信息', message: '提报成功!!' });
          this.$emit('close');
        } else {
          this.$notify.success({ type: '提示信息', message: '保存成功!!' });
          this.fromList.forEach(x => (x.disabled = true));
          this.newStatus = true;
          this.$emit('saveDialog');
        }
      }
    },
    // 提报
    async submit() {
      await this.saveDialog('submit'); //
    },
    closeDialog(param) {
      this.$emit('close');
    },

    confirmGdcx([param]) {
      this.isShowGdcx = false;
      // this.fromList.find(x => x.fieldName === 'roNo').initialValue = param['RO_NO'];
      this.fromList.find(x => x.fieldName === 'vin').initialValue = param['VIN'];
      this.fromList.find(x => x.fieldName === 'license').initialValue = param['LICENSE'];
      this.fromList.find(x => x.fieldName === 'ownerName').initialValue = param['OWNER_NAME'];
      this.fromList.find(x => x.fieldName === 'beforeEndDate').initialValue = param['WRT_END_DATE'];
      this.fromList.find(x => x.fieldName === 'beforeBeginDate').initialValue = param['WRT_BEGIN_DATE'];
      this.roNo = param['RO_NO'];
      // this.fromList.find(x => x.fieldName === 'beforeBeginDate').initialValue = param['MILEAGE'];
      // this.fromList.find(x => x.fieldName === 'beforeEndDate').initialValue = param['MILEAGE'];
    }
  }
};
</script>
